package com.zhongya.example.view

import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.zhongya.example.R
import kotlin.math.atan2
import kotlin.properties.Delegates

class AliPayView : View {

    val mCentX = 100f
    val mCentY = 100f
    val mRadius = 100f
    var mNext = false


    lateinit var mCirclePath : Path
    lateinit var mDstPath : Path
    lateinit var mPaint : Paint
    lateinit var mPathMeasure : PathMeasure
    var mCurAnimValue by Delegates.notNull<Float>()

    constructor(context: Context) : super(context) {

    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        setLayerType(LAYER_TYPE_SOFTWARE,null)

        //画笔
        mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = 4f
        mPaint.color = Color.BLACK
        //路径
        mDstPath = Path()
        mCirclePath = Path()
        //画圆形
        mCirclePath.addCircle(mCentX,mCentY,mRadius,Path.Direction.CW)
        //画直线
        mCirclePath.moveTo(mCentX - mRadius/2,mCentY)
        mCirclePath.lineTo(mCentX,mCentY+mRadius/2)
        mCirclePath.lineTo(mCentX+mRadius/2,mCentY - mRadius/3)

        mPathMeasure = PathMeasure(mCirclePath,false)

        val animator = ValueAnimator.ofFloat(0f,2f)
        animator.repeatCount = ValueAnimator.INFINITE
        animator.addUpdateListener {
            mCurAnimValue =  animator.animatedValue as Float
            invalidate()
            Log.e("wzy","$mCurAnimValue")
        }
        animator.duration = 4000
        animator.start()

        animator.addListener(object : Animator.AnimatorListener{
            override fun onAnimationStart(animation: Animator?) {
            }

            override fun onAnimationEnd(animation: Animator?) {
            }

            override fun onAnimationCancel(animation: Animator?) {
            }

            override fun onAnimationRepeat(animation: Animator?) {
                mNext = false
                mPaint.color = Color.RED
            }

        })

    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //绘制路径动画
        canvas?.drawColor(Color.WHITE)
        if (mCurAnimValue < 1){
            val stop = mPathMeasure.length*mCurAnimValue
            mPathMeasure.getSegment(0f,stop,mDstPath,true)
        }else{
            if (!mNext){
                mNext = true
                mPathMeasure.getSegment(0f,mPathMeasure.length,mDstPath,true)
                mPathMeasure.nextContour()
            }
            val stop = mPathMeasure.length*(mCurAnimValue - 1)
            mPathMeasure.getSegment(0f,stop,mDstPath,true)
        }

        canvas?.drawPath(mDstPath,mPaint)

    }
}